package Ligacao;

import java.net.InetAddress;
import java.net.Socket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: nelson
 */
public class ServerBeta {
    private final int port = 9870;
    private final int buffer = 1500;

    public ServerBeta(){
        /*NOTHING TO DO*/
    }

    public void run(){
        try{
            runServer();
        } catch(Exception e){
            System.out.println("\n* layer1 server error\n* " + e);
        }
    }

    private void runServer() throws Exception{
        OutputStream outToLayer2;
        Socket outSocket;
        byte data[] = new byte[buffer];
        byte checksum[];
        DatagramPacket packet;
        DatagramSocket socket;

        byte[] senderIP;
        int senderPort;

        socket = new DatagramSocket(port);
        packet =  new DatagramPacket(data, data.length);

        /*CONEXAO A CAMADA SUPERIOR*/
        outSocket = new Socket("localhost", 9872);
        System.out.println("layer1server connected to layer2server");
        /*CRIAR OUTPUT STREAM ASSOCIADA AO SOCKET*/
        outToLayer2 = outSocket.getOutputStream();

        while(true){
            /*RECEBER DATAGRAMA*/
            socket.receive(packet);

            senderIP = packet.getAddress().getAddress();
            senderPort = packet.getPort();

            /*VERIFICAR INTEGRIDADE DOS DADOS*/

            /*INSERIR IP DE ORIGEM E ENVIAR DADOS PARA A CAMADA SUPERIOR*/
            data[2] = senderIP[0];
            data[3] = senderIP[1];
            data[4] = senderIP[2];
            data[5] = senderIP[3];
            outToLayer2.write(data, 2, packet.getLength() - 2);

        }
    }
}
